package ihm;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import remote.Tweet;

import client.Client;

public class Accueil extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = -5433836609502087335L;
	Client client;
	boolean connecte = false;

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				// On crée une nouvelle instance de notre JDialog
				Accueil fenetre = new Accueil();
				fenetre.setVisible(true);// On la rend visible
			}
		});
	}

	public Accueil() {
		super();
		try {
			client = new Client(this);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (NotBoundException e) {
			e.printStackTrace();
		}
		build();
		Identification();// On initialise notre fenêtre
	}

	private void build() {
		setTitle("Tweeter");
		setSize(800, 600);
		setLocationRelativeTo(null);
		setResizable(false);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	@SuppressWarnings("static-access")
	public void accueilTweet(String tag) {
		this.getContentPane().removeAll();
		this.setLayout(new BorderLayout());
		topView();
		JPanel bot = new JPanel();
		final JTextArea tField = new JTextArea("Champs pour tweeter", 4, 40);
		final JTextField tagField = new JTextField("Tag", 12);
		bot.setPreferredSize(new Dimension(getContentPane().WIDTH, 130));
		Button tIButton = new Button("Ajouter Image");
		Button tButton = new Button("Tweeter");
		JPanel jp = new JPanel();
		jp.setLayout(new BoxLayout(jp, BoxLayout.Y_AXIS));

		if (connecte) {
			jp.add(tagField);
			jp.add(tField);

			tButton.setPreferredSize(new Dimension(100, 50));
			bot.add(new JScrollPane(tField));

			bot.add(jp);
			bot.add(tIButton);
			bot.add(tButton);
		}

		afficherTweet(tag, 20);
		this.add("South", bot);
		this.getContentPane().validate();

		tButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				String l = tField.getText();
				String tag = tagField.getText();
				if (!l.equals("") && !tag.equals(""))
					try {
						client.tweeter(new Tweet(tag, l));
						accueilTweet(null);

					} catch (RemoteException e1) {
						e1.printStackTrace();
					}
			}
		});

	}

	@SuppressWarnings("static-access")
	private void topView() {
		JPanel jp = new JPanel();
		jp.setPreferredSize(new Dimension(getContentPane().WIDTH, 60));
		JLabel tagl = new JLabel("Trier par tag:");
		final JTextField tagTop = new JTextField("", 6);
		Button buttonS = new Button("Trier");
		jp.add(tagl);
		jp.add(tagTop);
		jp.add(buttonS);
		jp.add(new JLabel("          "));
		Button button = new Button("Deconnexion");
		Button buttonConnecter = new Button("Se connecter");
		Button buttonFollow = new Button("Suivre");
		final JTextField followTop = new JTextField("", 6);
		if (connecte) {

			JLabel follow = new JLabel("Suivre un User:");
			jp.add(follow);
			jp.add(followTop);
			jp.add(buttonFollow);
			jp.add(new JLabel("          "));

			jp.add(button);
		} else {
			jp.add(buttonConnecter);
		}
		final JLabel validatiofollow = new JLabel("");
		validatiofollow.setForeground(Color.green);
		jp.add(validatiofollow);
		jp.setBackground(Color.white);
		this.add(BorderLayout.NORTH, jp);

		button.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					client.deconnexion();
					connecte=false;
					Identification();
				} catch (RemoteException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();

				}
			}
		});

		buttonConnecter.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				Identification();
			}
		});

		buttonS.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				String tagt = tagTop.getText();
				if (tagt.equals(""))
					accueilTweet(null);
				else
					accueilTweet(tagt);

			}
		});

		buttonFollow.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				String f = followTop.getText();
				if (!f.equals(""))
					try {
						client.follow(f);
						validatiofollow
								.setText(f
										+ " a bien été rajouté à la liste d'utilisateur que vous suivez");
					} catch (RemoteException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

			}
		});
	}

	private void afficherTweet(String tagASuivre, int x) {
		List<Tweet> tweets = new ArrayList<Tweet>();
		try {
			if (tagASuivre == null) {
				tweets = client.publicAccess.getRecent(x);
			} else
				tweets = client.publicAccess.getRecent(tagASuivre, x);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JPanel j = new JPanel();
		j.setBackground(Color.white);
		for (Tweet t : tweets) {
			JPanel jp = new JPanel();
			JLabel auteur = new JLabel("   (" + t.getAuthor() + ") ");
			JLabel tag = new JLabel("#" + t.getHtag() + ": ");
			JLabel content = new JLabel(t.getContent());
			auteur.setFont(new Font("Sans Serif", Font.BOLD, 18));
			tag.setFont(new Font("Sans Serif", Font.ITALIC, 18));
			tag.setForeground(Color.blue);
			content.setFont(new Font("Sans Serif", Font.BOLD, 18));
			jp.add(auteur);
			jp.setAlignmentX(LEFT_ALIGNMENT);
			jp.add(tag);
			jp.add(content);
			j.add(new JLabel("     "));
			jp.setLayout(new BoxLayout(jp, BoxLayout.X_AXIS));
			jp.setBackground(Color.white);
			j.add(jp);

		}
		j.setLayout(new BoxLayout(j, BoxLayout.Y_AXIS));
		this.add(BorderLayout.CENTER, new JScrollPane(j));

	}

	private void Identification() {
		this.getContentPane().removeAll();
		this.getContentPane().repaint();
		this.setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		this.getContentPane().setBackground(Color.white);
		JLabel title = new JLabel("Tweeter");
		title.setFont(new Font("Sans Serif", Font.BOLD, 35));
		title.setForeground(Color.blue);
		c.gridwidth = 4;
		c.gridx = 1;
		c.gridy = 0;
		this.add(title, c);
		c.gridx = 0;
		c.gridy = 1;
		this.add(new JLabel("    "), c);
		c.gridx = 0;
		c.gridy = 2;
		this.add(new JLabel("    "), c);
		c.gridwidth = 2;
		c.gridx = 0;
		c.gridy = 3;
		JLabel inscription = new JLabel("Inscription");
		inscription.setFont(new Font("Sans Serif", Font.BOLD, 22));
		inscription.setForeground(Color.blue);
		this.add(inscription, c);
		c.gridx = 4;
		JLabel connection = new JLabel("Connexion");
		connection.setForeground(Color.blue);
		connection.setFont(new Font("Sans Serif", Font.BOLD, 22));
		this.add(connection, c);
		c.gridx = 0;
		c.gridy = 4;
		this.add(new JLabel("    "), c);
		c.gridy = 4;
		this.add(new JLabel("    "), c);

		c.gridx = 4;
		c.gridy = 5;
		final JLabel cError = new JLabel(" ");
		cError.setForeground(Color.red);
		this.add(cError, c);
		c.gridx = 0;
		final JLabel iError = new JLabel(" ");
		iError.setForeground(Color.red);
		this.add(iError, c);
		c.gridwidth = 1;
		c.gridx = 0;
		c.gridy = 6;
		this.add(new JLabel("Login: "), c);
		c.gridx = 1;
		c.gridy = 6;
		final JTextField login = new JTextField("", 10);
		this.add(login, c);
		c.gridx = 0;
		c.gridy = 7;
		this.add(new JLabel("Password: "), c);
		final JPasswordField password = new JPasswordField("", 10);
		c.gridx = 1;
		c.gridy = 7;
		this.add(password, c);
		c.gridx = 0;
		c.gridy = 8;
		this.add(new JLabel("Ressaisir le Password: "), c);
		final JPasswordField password2 = new JPasswordField("", 10);
		c.gridx = 1;
		c.gridy = 8;
		this.add(password2, c);
		c.gridx = 1;
		c.gridy = 9;
		Button iButton = new Button("S'inscrire");
		this.add(iButton, c);
		c.gridx = 3;
		c.gridy = 6;
		this.add(new JLabel("                                    "), c);
		c.gridx = 4;
		c.gridy = 6;
		this.add(new JLabel("Login: "), c);
		final JTextField loginC = new JTextField("", 10);
		c.gridx = 5;
		c.gridy = 6;
		this.add(loginC, c);
		c.gridx = 4;
		c.gridy = 7;
		this.add(new JLabel("Password: "), c);
		final JPasswordField passwordC = new JPasswordField("", 10);
		c.gridx = 5;
		c.gridy = 7;
		this.add(passwordC, c);
		c.gridx = 5;
		c.gridy = 9;
		Button cButton = new Button("Se Connecter");
		this.add(cButton, c);
		c.gridwidth = 4;
		c.gridx = 1;
		c.gridy = 10;
		this.add(new JLabel("  "), c);
		c.gridy = 11;
		this.add(new JLabel("  "), c);
		c.gridy = 12;
		this.add(new JLabel("  "), c);
		c.gridy = 13;
		this.add(new JLabel("  "), c);
		c.gridy = 14;
		this.add(new JLabel("  "), c);
		c.gridy = 15;
		this.add(new JLabel("  "), c);

		c.gridy = 16;
		Button libreUserButton = new Button(
				"Se connecter en tant qu'utilisateur Libre");
		this.add(libreUserButton, c);
		this.getContentPane().validate();
		cButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				String login = loginC.getText();
				String password = new String(passwordC.getPassword());
				boolean b = false;
				if (!login.equals("") && !password.equals(""))
					try {
						b = client.connexion(login, password);
						connecte = true;
					} catch (RemoteException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				if (b)
					accueilTweet(null);
				else
					cError.setText("Mauvais login/password");
			}
		});
		
		libreUserButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				accueilTweet(null);
			}
		});

		iButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				String l = login.getText();
				String p = new String(password.getPassword());
				String p2 = new String(password2.getPassword());
				boolean b = false;
				if (!l.equals("") && !p.equals("") && p.equals(p2))
					try {
						b = client.inscription(l, p);
						if (b) {
							client.connexion(l, p);
							connecte = true;
						}

					} catch (RemoteException e1) {
						// TODO Auto-generated catch block
						iError.setText(e1.toString());
						e1.printStackTrace();
					} catch (IOException e1) {
						iError.setText(e1.toString());
						e1.printStackTrace();
					}
				else if (!p.equals(p2))
					iError.setText("Les mots de passe doivent etre identiques");
				else
					iError.setText("Tous les champs doivent etre remplis");
				if (b)
					accueilTweet(null);
				else if (!l.equals("") && !p.equals("") && p.equals(p2))
					iError.setText("Login non disponible");
			}
		});

	}

}